#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include<sys/types.h>
// 计算f(x)（阶乘函数）
int compute_fx(int x) {
    if (x < 1) return -1; // 错误处理
    int result = 1;
    for (int i = 2; i <= x; i++) {
        result *= i;
    }
    return result;
}

// 计算f(y)（类斐波那契数列）
int compute_fy(int y) {
    if (y < 1) return -1; // 错误处理
    int a = 1, b = 1, temp;
    if (y == 1 || y == 2) return 1;
    for (int i = 3; i <= y; i++) {
        temp = a + b;
        a = b;
        b = temp;
    }
    return b;
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s x y\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int x = atoi(argv[1]);
    int y = atoi(argv[2]);

    // 创建两个管道，分别用于f(x)和f(y的结果传递
    int pipe_fx[2], pipe_fy[2];
    if (pipe(pipe_fx) == -1 || pipe(pipe_fy) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // 创建进程A：计算f(x)
    pid_t pid_fx = fork();
    if (pid_fx == 0) {
        close(pipe_fx[0]); // 关闭读端
        int result = compute_fx(x);
        write(pipe_fx[1], &result, sizeof(int));
        close(pipe_fx[1]);
        exit(EXIT_SUCCESS);
    } else if (pid_fx < 0) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    // 创建进程B：计算f(y)
    pid_t pid_fy = fork();
    if (pid_fy == 0) {
        close(pipe_fy[0]); // 关闭读端
        int result = compute_fy(y);
        write(pipe_fy[1], &result, sizeof(int));
        close(pipe_fy[1]);
        exit(EXIT_SUCCESS);
    } else if (pid_fy < 0) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    // 父进程：接收数据并计算f(x,y)
    close(pipe_fx[1]); // 关闭写端
    close(pipe_fy[1]);

    int fx, fy;
    read(pipe_fx[0], &fx, sizeof(int));
    read(pipe_fy[0], &fy, sizeof(int));

    printf("f(%d) = %d\nf(%d) = %d\nf(x,y) = %d + %d = %d\n",
           x, fx, y, fy, fx, fy, fx + fy);

    close(pipe_fx[0]);
    close(pipe_fy[0]);

    // 等待子进程结束
    waitpid(pid_fx, NULL, 0);
    waitpid(pid_fy, NULL, 0);

    return EXIT_SUCCESS;
}
